package reentrantlock;

/**
 * 自定义的可重入锁
 */
public class MyReentrantLock implements MyLock {

    private boolean isLocked = false;

    private int lockedCount = 0;

    private Thread lockedBy = null;

    @Override
    public synchronized void lock() throws InterruptedException {
        Thread thread = Thread.currentThread();
        while (isLocked && lockedBy != thread) {
            wait();
        }
        isLocked = true;
        lockedBy = thread;
        lockedCount++;
    }

    @Override
    public synchronized void unlock() {
        Thread thread = Thread.currentThread();
        if (lockedBy == thread) {
            System.out.println(thread.getName() + "的lockedCount为" + lockedCount);
            if (lockedCount > 0) {
                lockedCount--;
            }
            if (lockedCount == 0) {
                System.out.println(thread.getName() + "释放锁");
                isLocked = false;
                notify();
            }
        }
    }
}
